<template>
  <div>
    <el-table
      v-table-style
      header-row-class-name="common-list-table-header base-table-header-v4"
      row-class-name="base-table-row-v4"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="data"
      :stripe="stripe"
      :border="border">
      <el-table-column type="selection" align="center" width="48"></el-table-column>
      <el-table-column fixed='left' type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}_${uuid()}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :width="column.width"
        :min-width="column.minWidth || '110px'"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <!-- start 物料名称 -->
          <template v-if="column.fieldName === 'name' && !scope.row.isReplaced">
            <biz-remote-select
              :placeholder="$t('common.placeholder.select')"
              :value="[scope.row]"
              :remote-method="fetchMaterial"
              @input="chooseMaterial($event, scope.row, scope.$index)"
            >
              <div class="search-in-part-item" slot="option" slot-scope="{ option }">
                <template v-if="option.name && !loading">
                  <p>{{$t('common.form.preview.materialReturn.tableLabel1')}}：<span>{{ option.name }}</span></p>
                  <p>{{$t('common.form.preview.materialReturn.colum1')}}：<span>{{ option.sn }}</span></p>
                  <p>{{$t('common.form.preview.materialReturn.tableLabel4')}}：<span>{{ option.property }}</span></p>
                </template>
                <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') :$t('common.base.tip.noData') }}</p>
              </div>
            </biz-remote-select>
          </template>
          <!-- start 申请数量 -->
          <template v-else-if="column.fieldName === 'number' && !scope.row.isReplaced ">
            <el-input-number v-model="scope.row.number" step-strictly controls-position="right" :min="1" :max="scope.row.availableNum" :disabled="scope.row.isSnManage">
            </el-input-number>
          </template>
          <!-- end 申请数量 -->
          <!-- start物料SN -->
          <template v-else-if="column.fieldName === 'SN' && !scope.row.isReplaced && scope.row.snManage === '是'">
            <el-input v-model="scope.row.SN" :placeholder="$t('common.placeholder.inputSomething', {data1:column.fieldName})"></el-input>
          </template>
          <!-- end 物料SN -->
          <!-- start 操作 -->
          <template v-else-if="column.fieldName === 'action'">
            <el-button v-if="!scope.row.isReplaced" class="text-danger" type="text" size="mini" @click="deleteItem(scope)">{{$t('common.base.delete')}}</el-button>
          </template>
          <!-- end 操作 -->
          <!-- start 富文本 -->
          <template v-else-if="column.setting && column.setting.originalFormType === 'richtext'">
            <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
              <span v-if="scope.row && scope.row.attribute && scope.row.attribute[column.fieldName]">{{$t('common.base.view')}}</span>
            </div>
          </template>
          <!-- end 富文本 -->
          
          <!-- end 物料名称 -->
          <template v-else>{{ $formatFormField(column, scope.row) }}</template>

        </template>
      </el-table-column>
    </el-table>
    <!-- start sn弹窗 -->
    <material-sn-dialog 
      ref="materialSnDialog" 
      :data="data" 
      @changeSn="changeSn"
    />
    <!-- end sn弹窗 -->

    <!-- 富文本弹窗 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* util */
import MathUtil from '@src/util/math';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH, MATERIAL_LIST_MAX } from '@src/model/const/Number';

/* component */
import SearchMaterialSelect from '@src/component/form/common/warehouse/SearchMaterialSelect.vue';
import MaterialSnDialog from './MaterialSnDialog';

import { getCustomerArrdess } from '@src/filter/fmt.js';
import { handleSelectData } from '@src/util/languages.js';
import { materialSpecialHandlingFieldName } from '@src/modules/task/view/components/materialUtil.js';
import { getRootWindow } from '@src/util/dom'
import { GrayFunctionEnum } from '@model/grayFunction'

export default {
  name: 'material-table-new-version',
  provide: {
    // 是否需要确认库存
    ifCheckStockNum: false, 
  },
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    data: {
      type: Array,
      default: () => ([])
    },
    // colums: {
    //   type: Array,
    //   default: () => ([])
    // },
    border: {
      type: Boolean,
      default: false
    },
    stripe: {
      type: Boolean,
      default: false
    },
    // 可选择物料
    canSelectPart: {
      type: Boolean,
      default: false
    },
    // 物料配置
    partConfig: {
      type: Object,
      default: () => ({})
    },
    // 物料配置
    materConfig: {
      type: Object,
      default: () => ({})
    },
    type: {
      type: String,
      default: ''
    },
    card: {
      type: Object,
      default: () => ({})
    },
    warehouseId: [String, Number], // 仓库id，查询物料库存用
    positionId: [String, Number], // 仓位id，查询物料库存用
    warehouseName: [String],
    positionName: [String]
  },
  inject: ['initData'],
  components: {
    [SearchMaterialSelect.name]: SearchMaterialSelect,
    [MaterialSnDialog.name]: MaterialSnDialog
  },
  data() {
    return {
      emptyData: {
        salePrice: 0,
        name: '',
        sort: '',
        unit: '',
        id: '',
        snList: [],
        number: 0,
        property: '',
        sn: '',
        snManage: '',
        warehouseId: '',
        positionId: '',
        warehouseName: '',
        positionName: '',
        materialId:'',
        materialSn:'',
        SN:'',
        image:[],
        images:[],
        machine: null
      },
      loading: false,
      ifCheckStockNum: false,
      multipleSelection:[]
    }
  },
  computed: {
    batchSelectGray () {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.BATCH_PERIOD] ?? true // 批次号灰度
    },
    showRepertory() {
      let idx = this.columns.findIndex(item => item.fieldName == 'repertory')
      return idx > -1;
    },
    // 关联物料字段
    relationMaterialFields() {
      return this.field?.setting?.materialFields || [];
    },
    columns() {
      let columns = [
        ...this.relationMaterialFields,
        {
          displayName: 'SN',
          fieldName: 'SN',
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel14'),
          fieldName: 'batchNumber'
        }, 
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel10'),
          fieldName: 'number',
          minWidth: '110px',
        },
        {
          displayName: this.$t('common.base.operation'),
          fieldName: 'action',
          fixed: 'right',
          minWidth: '70px'
        }
      ]
      if(!this.showWarrantyStatus) {
        columns = columns.filter(item => item.fieldName !== 'warrantyStatus')
      }

      if(!this.batchSelectGray) {
        columns = columns.filter(item => item.fieldName !== 'batchNumber')
      }

      return columns;
    }, 
    task() {
      return this.initData?.task || {};
    }   
  },
  methods: {
    toggleSelection(rows) {
      this.$refs.multipleTable.toggleRowSelection(rows);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    openSnDialog(type, row, index) {
      this.$refs.materialSnDialog.open(type, row, index)
    },
    changeSn(data) {
      this.data = data
    },
    /**
     * @description 添加一条表格数据
    */
    add() {
      if (this.data.length >= MATERIAL_LIST_MAX) {
        return this.$message({
          showClose: true,
          message: this.$t('common.form.preview.materialVerifyEliminate.addMaterialMax', {max: MATERIAL_LIST_MAX}),
          type: 'error'
        })
      }
      
      let newData = this.data.slice()
      newData.push({...this.emptyData});
      this.$emit('input', newData,'add')
    },
    /**
    * @description 修改预计用量
    */
    handlePreNum(item) {
      if (this.type == 'service') return this.handleServiceNum(item);
      return this.handleSparepartNum(item);
    },
    /**
    * @description 修改服务项目预计用量
    */
    handleServiceNum(item) {
      let value = Number(item.preNum);
      let count = MathUtil.decimalNumber(value);
      let max = PART_SERVICE_LIST_PRENUM_MAX_LENGTH;

      if (value <= 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.rightNumTip'));
        item.preNum = 1;
        return;
      }

      if (value > max) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.applyNumMax', {max}));
        item.preNum = max;
        return;
      }

      if (count > 2) {
        this.$platform.alert(this.$t('common.form.tip.materialReturn.tips9'));
        item.preNum = 1;
      }
    },
    /**
    * @description 修改物料预计用量
    */
    handleSparepartNum(item) {
      let value = Number(item.preNum);
      let count = this.decimalNumber(value);
      let max = item.repertoryCount || PART_SERVICE_LIST_PRENUM_MAX_LENGTH;
      let min = max ? (max > 1 ? 1 : max) : 1;

      if (value <= 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.rightNumTip'));
        item.preNum = min;
        return;
      }

      if (value > max) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.applyNumMax', {max}));
        item.preNum = max;
        return;
      }
      
      if (count != -1 && count == 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.greaterThanZeroTip1'));
        item.preNum = min;
        return;
      }
      
      if (count != -1 && count != 0) {
        this.$platform.alert(this.$t('common.form.preview.materialVerifyEliminate.greaterThanZeroTip2', {count}));
        item.preNum = min;
      }
    },
    /**
    * @description 预计用量小数位
    */
    decimalNumber(num) {
      let { sparepart2, precision } = this.partConfig;
      let count = MathUtil.decimalNumber(num);

      if(!sparepart2 && count != 0) return 0;
      if(precision >= count) return -1;
      return precision;
    },
    /**
    * @description 选择仓库
    */
    chooseRepertory(value, row) {
      row.repertoryId = value.repertoryId;
      row.repertoryCount = value.repertoryCount;
    },
    hasRow(value) {
      return this.data.some(item => item.materialId === value);
    },
    /**
     * @description 搜索物料
    */
    async fetchMaterial(value) {
      try {
        this.loading = true;
        const { keyword, pageNum, pageSize } = value
        let params = {
          keyword,
          pageNum,
          pageSize,
          needAreaPrice: this.field?.setting?.useRegionalPricing || false,
          address: getCustomerArrdess(this.task),
          materialStatus: true
        }
        let res = await WareHouseApi.getMaterialList(params);
        this.loading = false;
        if (!res.success) return;
        res.data.list = res.data.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item,
          }
        });
        return res.data;
      } catch (error) {
        this.loading = false;
        console.warn('fetchMaterial -> error', error);
      } 
    },
    // 选择物料
    chooseMaterial(value, row, index) {
      let newRow = row;
      let selectedMaterial = value?.[0] || {};
      if(!selectedMaterial.id) return;
      // 判断当前选择的物料是否已经存在, 排除本身
      let idx = this.data.findIndex(item => item.id == selectedMaterial.id);
      if(idx > -1 && idx != index) return this.$platform.toast(this.$t('common.form.preview.materialVerifyEliminate.tip2'), 'warning');

      Object.keys(selectedMaterial).forEach(key => {
        let isPeriodManageSub = selectedMaterial.isPeriodManage;
        this.columns.forEach(zitem => {
          if (materialSpecialHandlingFieldName.includes(zitem.fieldName)) {
            if (zitem.isSystem === 0 && selectedMaterial?.attribute?.[zitem.fieldName]) {
              selectedMaterial.attribute[zitem.fieldName] = handleSelectData(
                zitem,
                selectedMaterial?.attribute?.[zitem.fieldName]
              );
            } else {
              selectedMaterial[zitem.fieldName] = handleSelectData(
                zitem,
                selectedMaterial?.[zitem.fieldName]
              );
            }
          }
        });
        if (!selectedMaterial['shelfLifeBk']) {
          selectedMaterial['shelfLifeBk'] = selectedMaterial.shelfLife;
        }
        if (!selectedMaterial['shelfLifeValueBk']) {
          selectedMaterial['shelfLifeValueBk'] = selectedMaterial.shelfLifeValue;
        }
        
        if (selectedMaterial?.shelfLifeValue && selectedMaterial?.shelfLife && Boolean(isPeriodManageSub)) {
          // 取备份的值，防止重复拼接
          selectedMaterial.shelfLife = `${selectedMaterial.shelfLifeValueBk}${selectedMaterial.shelfLifeBk}`
        } else {
          selectedMaterial.shelfLife = '';
        }

        newRow[key] = selectedMaterial[key];
      })

      Object.keys(this.emptyData).forEach(key => {
        if (key == 'number') {
          newRow[key] = 1;
        } else if(key === 'SN'){
          newRow[key] = '' 
        } else if(key == 'sort') {
          newRow[key] = selectedMaterial.type || '';
        } else if(key === 'snList') {
          newRow[key] = selectedMaterial.snList || [];
        } else if(key === 'warehouseId') {
          newRow[key] = this.warehouseId
        } else if(key === 'warehouseName') {
          newRow[key] = this.warehouseName
        } else if(key === 'positionName') {
          newRow[key] = this.positionName
        } else if(key === 'positionId') {
          newRow[key] = this.positionId
        } else if(key === 'salePrice') {
          newRow[key] = selectedMaterial.salePrice || 0
        } else {
          newRow[key] = selectedMaterial[key];
        }
      })
      
      let newData = this.data.slice();
      newData[index] = newRow
      this.$emit('input', newData)
    },
    outsideGetTableData() {
      return this.multipleSelection || []
    },
    outsideSetTableData(value = []) {
      // 会报错 直接修改父组件数据
      // this.data = value
    },
    deleteItem(scope) {
      let index = scope.$index;
      let row = scope.row;
      let newData = this.data.slice();
      newData.splice(index, 1)
      this.$refs.multipleTable.toggleRowSelection(row, false);
      this.$emit('input', newData)
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  }
}
</script>

<style lang="scss">
  .search-in-part-item {
    padding: 8px 5px 8px 0;
    overflow: hidden;
    max-width: 260px;
    p {
      /*@include text-ellipsis();*/
      line-height: 20px;
      margin: 0 16px 0 0;
      // color: $text-color-primary;
      white-space: initial;
      span {
        // color: $text-color-regular;
      }
    }

    .no_empty {
      padding: 0;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
  }
</style>

<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}

.el-table {
  &::before {
    content: "";
  }
}
</style>